<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <title>主力资金流入</title>
  <script src="/app/stock/echarts.min.js"></script>
  <style>
    /* Set HTML, body, and #treemap to cover the full screen */
    html,
    body {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;

    }

    #treemap {
      width: 100%;
      height: 100vh;
      /* Full viewport height */
    }
  </style>
</head>

<body>
  <div id="treemap"></div>

  <script>
    let chart;

    // 定义函数以从URL接口加载数据并渲染图表
    async function fetchDataAndRender() {
      // Set the document's title to the current date and time
      document.title = "主力资金流入-概念 " + getFormattedDateTime();
      try {
        // 替换为你的API接口地址
        let headersList = {
          "Accept": "*/*",
          "Authorization": `${localStorage.getItem('authToken')}`
        }

        let response = await fetch(
          "/api/trading/sector_funds2", {
            method: "GET",
            headers: headersList
          });
        const data = await response.json();

        function formatNumber(value) {
          if (Math.abs(value) >= 100000000) {
            return (value / 100000000).toFixed(2) + '亿';
          } else if (Math.abs(value) >= 10000) {
            return (value / 10000).toFixed(2) + '万';
          } else {
            return value.toString();
          }
        }
        // 将API返回的数据格式化为treemap所需的格式
        // Step 1: Find max positive and min negative net inflow
        const maxNetInflow = Math.max(...data.map(item => item["今日主力净流入-净额"]).filter(val => val > 0));
        const minNetInflow = Math.min(...data.map(item => item["今日主力净流入-净额"]).filter(val => val < 0));

        const treemapData = data.map(item => {

          const netInflow = item["今日主力净流入-净额"];
          let color_area;
          let color_text;
          if (netInflow > 0) {
            // Scale transparency relative to maxNetInflow (positive)
            const opacity = netInflow / maxNetInflow * 0.8 + 0.2;
            color_area = `rgba(255, 0, 0, ${opacity})`; // Red for positive inflow
            color_text = `rgba(0, 128, 0, ${opacity})`
          } else if (netInflow < 0) { // Scale transparency relative to minNetInflow (negative) 
            const opacity = Math.abs(netInflow / minNetInflow) * 0.8 + 0.2;
            color_area = `rgba(0, 128, 0, ${opacity})`; // Greenfor negative inflow
            color_text = `rgba(255, 0, 0, ${opacity})`
          } else {
            color_area = 'rgba(128, 128, 128, 0.8)'; // Gray for zero inflow
          }
          if ((item["今日涨跌幅"] < 0 && item["今日主力净流入-净额"] < 0) || (item["今日涨跌幅"] > 0 && item["今日主力净流入-净额"] > 0))
            color_text = 'rgba(255, 255, 255, 1)'; // White text for positive inflow
          return {
            name: item["名称"],
            value: Math.abs(item["今日主力净流入-净额"]), //面积大小基于今日主力净流入 - 净额
            label: {
              show: true,
              formatter: function () {
                return `{title|${item["名称"]}}\n\n{rate|${item["今日涨跌幅"]}%}\n\n${formatNumber(item["今日主力净流入-净额"])}`
              },
              rich: {
                rate: {
                  fontSize: 18, // Title font size
                  color: color_text, // Title color 
                  fontWeight: 'Heavy',
                },
                title: {
                  fontSize: 24, // Title font size
                  fontWeight: 'bold',
                  color: 'white' // Title color
                },
              },
              textStyle: {
                color: 'white', // 可设置颜色
                fontSize: 12 // 其他文本内容的默认字体大小
              }
            },
            tooltip: {
              formatter: `
            名称: ${item["名称"]}<br />
            涨跌幅: ${item["今日涨跌幅"]}%<br />
            主力净流入-净额: ${formatNumber(item["今日主力净流入-净额"])}<br />
            主力净流入-净占比: ${item["今日主力净流入-净占比"]}%<br />`
              // `
              // 超大单净流入-净额: ${formatNumber(item["今日超大单净流入-净额"])}<br />
              // 超大单净流入-净占比: ${item["今日超大单净流入-净占比"]}%<br />
              // 大单净流入-净额: ${formatNumber(item["今日大单净流入-净额"])}<br />
              // 大单净流入-净占比: ${item["今日大单净流入-净占比"]}%<br />
              // 中单净流入-净额: ${formatNumber(item["今日中单净流入-净额"])}<br />
              // 中单净流入-净占比: ${item["今日中单净流入-净占比"]}%<br />
              // 小单净流入-净额: ${formatNumber(item["今日小单净流入-净额"])}<br />
              // 小单净流入-净占比: ${item["今日小单净流入-净占比"]}%<br />
              // 主力净流入最大股: ${item["今日主力净流入最大股"]}
              // `
            },
            itemStyle: {
              color: color_area
            }
          };
        });

        // 配置 treemap 图表的选项
        const option = {
          // title: {
          //   text: '今日主力净流入分布图',
          //   left: 'center'
          // },
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}'
          },
          series: [{
            type: 'treemap',
            data: treemapData,
            //leafDepth: 1, // 设置为1，只展示一层数据
            label: {
              show: true,
              formatter: '{b}\n{c}'
            },
            itemStyle: {
              borderColor: 'grey',
              borderWidth: 0.5
            },
            width: "100%",
            height: "100%",
            roam: "zoom",
            scaleLimit: {
              min: 1,
              max: 3
            },
            nodeClick: false,
            breadcrumb: {
              show: false
            }
          }]
        };

        // 使用设置好的配置项渲染图表
        chart.setOption(option);


      } catch (error) {
        console.error('数据加载失败:', error);
      }
    }

    // Format current date and time
    function getFormattedDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    }

    // Initialize ECharts instance if not already initialized
    if (!chart) {
      chart = echarts.init(document.getElementById('treemap'));
      // Make chart responsive
      window.addEventListener('resize', () => {
        chart.resize();
      });
    }
    // Run fetchDataAndRender when the page loads
    window.onload = async function () {
      await fetchDataAndRender(); // Initial load
      setInterval(fetchDataAndRender, 600000); // Refresh every 60 seconds
    };
  </script>
</body>

</html>